package linearList;

/**
 * Created by eason on 2017/11/18.
 * 双向链表
 * 说明 链表从0开始
 */
public class LinkedList<E>  implements MyList<E> {

    transient Node<E> first;//
    transient Node<E> last; //
    transient int size = 0; //长度
    public LinkedList() {
    }

    @Override
    public Integer size() {
        return size;
    }

    @Override
    public E get(int i) {
        if(i<0 ||i>=size){
            throw new IndexOutOfBoundsException();
        }
        return  getNode(i).item;
    }

    @Override
    public boolean add(E object) {
        final  Node<E> l =last;
       Node<E>  newNode =new Node<E>(l,object,null);
        last = newNode;
        if(l == null){
            first = newNode;
        }else {
          l.next =newNode;
        }
        size ++;
        return true;
    }

    /***
     * 双向链表的删除
     * @param i
     * @return
     */
    @Override
    public boolean remove(int i) {
        if(i>size || i<0){
            throw new  IndexOutOfBoundsException();
        }


        return false;
    }

    /**
     * 置空操作
     * @return
     */
    @Override
    public boolean empty() {
        return false;
    }


    private class Node<E>{
        E item;
        Node<E> next;
        Node<E> prev;
        Node(Node<E> prev,E element,Node next){
            this.prev =prev;
            this.item =element;
            this.next =next;
        }
    }
    private Node<E> getNode(int i){
        int  position =0;
        Node<E> node =null;

        while(position<=i) {
            if (position != 0) {
                node =node.next;
                position++;
            } else {
                node = getFirstNode();
                position++;
            }
        }
        return (Node<E>) node;
    }

    private Node<E>  getFirstNode(){
        return first;
    }
}
